package com.kl.controller;


import com.alibaba.druid.util.StringUtils;
import com.kl.domain.UserDTO;
import com.kl.em.ConstantEnum;
import com.kl.em.Result;
import com.kl.entity.SeckillCoupon;
import com.kl.service.ISeckillCouponService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2021-10-30
 */
@RestController
@RequestMapping("/seckill-coupon")
public class SeckillCouponController {


    @Resource
    private ISeckillCouponService iSeckillCouponService;

    @Resource
    private RedisTemplate redisTemplate;

    //获取要参与秒杀的优惠卷
   // @Scheduled(cron = "0 30-59 * * * ? ")
    @GetMapping("selectSeckillCouponList/{id}")
    //@Scheduled(fixedDelay = 5000)
    public Result selectSeckillCouponList(){
        List<SeckillCoupon> seckillCoupons = iSeckillCouponService.selectSeckillCouponList();
        if (seckillCoupons == null){
            return Result.build(ConstantEnum.ERROR).setResult("没有秒杀的商品");
        }
        System.out.println("正在获取");
        return Result.build(ConstantEnum.SUCCESS).setResult(seckillCoupons);
    }


    //抢购 创建订单
    @GetMapping("createOrder")
    public Result createOrder(Long CouponsId,HttpServletRequest request) throws Exception {


        String token = null;
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length != 0) {
            Cookie[] var = cookies;
            int var2 = cookies.length;
            for (int var3 = 0; var3 < var2; var3++) {
                Cookie cookie = var[var3];
                if (cookie.getName().equals("token")) {
                    token = cookie.getValue();
                }
            }
            if (StringUtils.isEmpty(token)) {
                token = request.getHeader("token");
                if (StringUtils.isEmpty(token)) {
                    token = request.getParameter("token");
                }
            }
        }
        if ( org.apache.commons.lang3.StringUtils.isNoneBlank(token) && redisTemplate.boundHashOps("login_user").hasKey(token)){
            UserDTO userDTO =  (UserDTO)redisTemplate.boundHashOps("login_user").get(token);
            iSeckillCouponService.createOrder(CouponsId,userDTO);
            return Result.build(ConstantEnum.SUCCESS).setResult(userDTO);
        }

       return Result.build(ConstantEnum.ERROR).setResult("用户未登录");
    }




}
